<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>请求取消</title>
  <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.0.1/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
</head>
<body>
  <div class="container">
    <h2 class="page-header">axios取消请求</h2>
    <button class="btn btn-primary"> 发送请求 </button>
    <button class="btn btn-warning"> 取消请求 </button>
  </div>
  <script>
    // 获取按钮
    const btns = document.querySelectorAll('button');
    // 2. 声明全局变量
    let cancel = null;
    // 发送请求
    btns[0].onclick = function() {
      // 在请求前，检测上一次的请求是否已经完成
      if(cancel !== null) cancel(); // 如果上一次请求还在，那么取消上一次的请求
      axios({
        methos: 'GET',
        url: 'http://localhost:3000/posts',
        // 1. 添加配置对象的属性
        cancelToken: new axios.CancelToken(function(c) {
          // 3. 将c的值赋值给cancel
          cancel = c;
        })
      }).then(response => {
        console.log(response)
        // 将cancel的值初始化
        cancel = null;
      })
    }

    btns[1].onclick = function() {
      // cancel the request
      cancel();
    }

  </script>
</body>
</html>